<template>
  <div class="drawer-content-wrapper">
    <!-- 案件概览卡片 -->
    <div class="info-section">
      <h3 class="section-title">案件概览</h3>
      <div class="info-descriptions">
        <div class="overview-header">
          <h2>案号：{{ caseData.case_code }}</h2>
          <div class="overview-actions">
            <el-button type="primary" @click="handleEditCase">编辑案件</el-button>
            <el-button @click="handleAddProgress">添加进度</el-button>
          </div>
        </div>
        <div class="overview-info">
          <div class="info-item">
            <span class="label">接案日期:</span>
            <span class="value">{{ formatTime(caseData.entrust_date, 'date') }}</span>
          </div>
          <div class="info-item stage-info">
            <span class="label">代理阶段:</span>
            <div class="stage-container">
              <div class="stage-header">
                <span class="stage-name">{{ caseData.stage }}</span>
              </div>
            </div>
          </div>
          <div class="info-item progress-item">
            <span class="label"></span>
            <div class="progress-container">
              <div class="stage-progress-bar">
                <div
                  v-for="(stage, index) in stageProgress"
                  :key="index"
                  class="progress-stage"
                  :class="[stage.status, { active: stage.isCurrent }]"
                  :style="{ width: stage.width + '%' }"
                >
                  <span class="stage-text">{{ stage.name }}</span>
                  <div class="stage-dot"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 案件基本信息 -->
    <div class="info-section">
      <h3 class="section-title">案件基本信息</h3>
      <div class="info-descriptions">
        <CaseBasicInfo :case-data="caseData" :format-time="formatTime" />
      </div>
    </div>

    <!-- 平铺卡片布局，替代原来的标签页 -->
    <div class="cards-layout">
      <!-- 关联合同卡片 -->
      <div class="info-card contract-card">
        <h3 class="card-title">关联合同</h3>
        <div class="card-content">
          <ContractInfo
            :case-id="caseData.id"
            :contract-id="caseData.contract_id"
            @contract-linked="handleContractLinked"
          />
        </div>
      </div>

      <!-- 会员信息卡片 -->
      <div
        class="info-card membership-card"
        v-if="caseData.client_membership_info && caseData.client_membership_info.customer_id"
      >
        <h3 class="card-title">会员信息</h3>
        <div class="card-content">
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="会员状态">
              <el-tag :type="getMembershipTagType(caseData.client_membership_info.customer_status)">
                {{ caseData.client_membership_info.customer_status_name || '未设置' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客户等级">
              {{ caseData.client_membership_info.customer_level_name || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="客户类型">
              <el-tag
                :type="caseData.client_membership_info.customer_type === 15 ? 'info' : 'primary'"
              >
                {{
                  caseData.client_membership_info.customer_type_name ||
                  (caseData.client_membership_info.customer_type === 15 ? '个人' : '企业')
                }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="管家">
              {{ caseData.client_membership_info.manager_name || '未设置' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 当事人信息卡片 -->
      <div class="info-card parties-card">
        <h3 class="card-title">当事人信息</h3>
        <div class="card-content">
          <CaseParties
            :party-list="partyList"
            @add-party="handleAddParty"
            @edit-party="handleEditParty"
            @remove-party="handleRemoveParty"
          />
        </div>
      </div>

      <!-- 案件进度卡片 -->
      <div class="info-card progress-card">
        <h3 class="card-title">案件进度</h3>
        <div class="card-content">
          <CaseProgress
            :progress-list="progressList"
            @add-progress="handleAddProgress"
            @delete-progress="handleDeleteProgress"
          />
        </div>
      </div>

      <!-- 相关文档卡片 -->
      <div class="info-card documents-card">
        <h3 class="card-title">相关文档</h3>
        <div class="card-content">
          <CaseDocuments
            :case-id="caseData.id"
            :format-time="formatTime"
            @refresh-documents="handleRefreshDocuments"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import CaseBasicInfo from './CaseBasicInfo.vue'
  import CaseParties from './CaseParties.vue'
  import CaseProgress from './CaseProgress.vue'
  import ContractInfo from './ContractInfo.vue'
  import CaseDocuments from './CaseDocuments.vue'
  import CaseMembershipInfo from './CaseMembershipInfo.vue'
  import { getStageText } from '@/constants/lawcase'
  import { statusService } from '@/utils/statusService'
  import type { Party, Progress, LawCase } from '@/types'
  import type { CaseLawyer } from '@/types/lawcase'

  const props = defineProps<{
    caseData: LawCase
    partyList: Party[]
    lawyerList: CaseLawyer[]
    progressList: Progress[]
    formatTime: (time: number | string, format?: 'date' | 'datetime' | 'time') => string
  }>()

  // 添加调试日志
  console.log('CaseDetailDrawer组件接收到的数据:', {
    caseData: props.caseData,
    partyList: props.partyList,
    lawyerList: props.lawyerList,
    progressList: props.progressList,
  })

  const emit = defineEmits([
    'add-party',
    'edit-party',
    'remove-party',
    'add-lawyer',
    'set-main-lawyer',
    'remove-lawyer',
    'add-progress',
    'edit-case',
    'refresh-case',
  ])

  // 获取阶段进度条状态
  const getStageProgressStatus = (percentage: number) => {
    if (percentage === 100) {
      return 'success'
    } else if (percentage < 30) {
      return 'exception'
    }
    return ''
  }

  // 获取进度分组信息（复制自Lawcase.vue的PROGRESS_GROUPS）
  const PROGRESS_GROUPS = {
    诉前阶段: {
      statuses: ['准备阶段（未提交立案）', '起诉阶段（提交立案待受理）'],
      color: '#409EFF',
      description: '诉前阶段',
    },
    诉中阶段: {
      statuses: [
        '庭前阶段（立案受理未开庭）',
        '审判阶段（已开庭未出判决）',
        '庭后阶段（已判决未生效）',
      ],
      color: '#E6A23C',
      description: '诉中阶段',
    },
    诉后阶段: {
      statuses: ['执行阶段（判决生效）'],
      color: '#67C23A',
      description: '诉后阶段',
    },
    完结: {
      statuses: ['结案', '撤诉', '终止委托'],
      color: '#909399',
      description: '已完结',
    },
  }

  // 计算当前进度百分比
  const progressPercentage = computed(() => {
    const currentStatus = props.caseData.status
    let stageIndex = 0
    let stageProgress = 0

    // 遍历四个大阶段
    const stages = ['诉前阶段', '诉中阶段', '诉后阶段', '完结']

    for (let i = 0; i < stages.length; i++) {
      const stage = stages[i]
      const config = PROGRESS_GROUPS[stage as keyof typeof PROGRESS_GROUPS]
      if (config.statuses.includes(currentStatus)) {
        stageIndex = i
        // 计算在当前阶段内的进度
        const statusIndex = config.statuses.indexOf(currentStatus)
        stageProgress = ((statusIndex + 1) / config.statuses.length) * 25
        break
      }
    }

    // 计算总进度百分比
    return Math.min(stageIndex * 25 + stageProgress, 100)
  })

  // 计算进度条颜色
  const progressColor = computed(() => {
    const currentStatus = props.caseData.status

    for (const [group, config] of Object.entries(PROGRESS_GROUPS)) {
      if (config.statuses.includes(currentStatus)) {
        return config.color
      }
    }
    return '#409EFF'
  })

  // 计算进度文本
  const progressText = computed(() => {
    const currentStatus = props.caseData.status

    for (const [group, config] of Object.entries(PROGRESS_GROUPS)) {
      if (config.statuses.includes(currentStatus)) {
        return `${group}: ${currentStatus}`
      }
    }
    return currentStatus
  })

  // 计算三段式进度条状态
  const stageProgress = computed(() => {
    const status = props.caseData.status || ''

    const stages = [
      { name: '诉前阶段', key: 'pre-litigation', width: 25 },
      { name: '诉中阶段', key: 'litigation', width: 25 },
      { name: '诉后阶段', key: 'post-litigation', width: 25 },
      { name: '完结', key: 'completed', width: 25 },
    ]

    let currentStageIndex = 0

    // 根据当前状态确定阶段索引
    for (let i = 0; i < stages.length; i++) {
      const stage = stages[i]
      const config = PROGRESS_GROUPS[stage.name as keyof typeof PROGRESS_GROUPS]
      if (config?.statuses.includes(status)) {
        currentStageIndex = i
        break
      }
    }

    return stages.map((stage, index) => ({
      ...stage,
      status:
        index < currentStageIndex
          ? 'completed'
          : index === currentStageIndex
            ? 'current'
            : 'pending',
      isCurrent: index === currentStageIndex,
    }))
  })

  // 处理添加当事人
  const handleAddParty = () => {
    emit('add-party')
  }

  // 处理编辑当事人
  const handleEditParty = (row: Party) => {
    emit('edit-party', row)
  }

  // 处理移除当事人
  const handleRemoveParty = (row: Party) => {
    emit('remove-party', row)
  }

  // 处理添加律师
  const handleAddLawyer = () => {
    emit('add-lawyer')
  }

  // 处理设置主办律师
  const handleSetMainLawyer = (row: CaseLawyer) => {
    emit('set-main-lawyer', row)
  }

  // 处理移除律师
  const handleRemoveLawyer = (row: CaseLawyer) => {
    emit('remove-lawyer', row)
  }

  // 处理添加进度
  const handleAddProgress = () => {
    emit('add-progress')
  }

  // 获取会员状态标签类型
  const getMembershipTagType = (status?: string | number) => {
    if (statusService.isValidMemberStatus(status || 0)) {
      return 'success'
    } else if (statusService.isExpiredMemberStatus(status || 0)) {
      return 'warning'
    } else {
      return 'info'
    }
  }

  // 处理删除进度
  const handleDeleteProgress = () => {
    // 通知父组件刷新案件详情
    emit('refresh-case')
  }

  // 处理编辑案件
  const handleEditCase = () => {
    emit('edit-case')
  }

  // 处理合同关联完成事件
  const handleContractLinked = () => {
    // 通知父组件刷新案件详情
    emit('refresh-case')
  }

  // 处理刷新文档列表
  const handleRefreshDocuments = () => {
    // 通知父组件刷新案件详情
    emit('refresh-case')
  }

  // 根据状态获取CSS类名
  const getStatusClass = (status: string) => {
    const statusMap: Record<string, string> = {
      '准备阶段（未提交立案）': 'status-preparation',
      '起诉阶段（提交立案待受理）': 'status-filing',
      '庭前阶段（立案受理未开庭）': 'status-pre-trial',
      '审判阶段（已开庭未出判决）': 'status-trial',
      '庭后阶段（已判决未生效）': 'status-post-trial',
      '执行阶段（判决生效）': 'status-execution',
      结案: 'status-closed',
      撤诉: 'status-withdrawn',
      终止委托: 'status-terminated',
    }

    return statusMap[status] || ''
  }

  // 判断是否为紧急案件（开庭时间在3天内）
  const isUrgentCase = () => {
    if (!props.caseData.session_time) return false

    try {
      // 确保正确处理秒级时间戳
      const timeValue =
        typeof props.caseData.session_time === 'string'
          ? parseInt(props.caseData.session_time)
          : props.caseData.session_time

      // 检查是否是秒级时间戳（10位左右），如果是则转换为毫秒级
      let timestamp = timeValue
      if (typeof timestamp === 'number' && timestamp.toString().length <= 10) {
        timestamp = timestamp * 1000 // 秒级时间戳转换为毫秒级
      }

      const sessionDate = new Date(timestamp)

      // 检查是否是有效日期
      if (isNaN(sessionDate.getTime())) {
        return false
      }

      const now = new Date()
      const diffDays = Math.ceil((sessionDate.getTime() - now.getTime()) / (1000 * 3600 * 24))

      return diffDays > 0 && diffDays <= 3
    } catch (error) {
      return false
    }
  }
</script>

<style scoped>
  /* 使用全局drawer-content-wrapper样式，保持一致性 */

  /* 案件概览卡片 */
  .case-overview-card {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .overview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 10px;
  }

  .overview-header h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }

  .overview-actions {
    display: flex;
    gap: 10px;
  }

  .overview-info {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    row-gap: 10px;
  }

  .info-item {
    display: flex;
    flex-direction: column;
    min-width: 180px;
  }

  .info-item .label {
    font-size: 12px;
    color: #606266;
    margin-bottom: 4px;
  }

  .info-item .value {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }

  /* 紧急案件样式 */
  .info-item.urgent .value {
    width: 100%;
  }

  /* 状态标签样式 */
  .status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;
  }

  /* 阶段信息样式 */
  .stage-info {
    display: flex;
    flex-direction: column;
  }

  .stage-container {
    flex: 1;
  }

  .stage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .stage-name {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }

  .stage-name {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }

  .status-preparation {
    background-color: #e3f2fd;
    color: #1976d2;
    border-left: 3px solid #2196f3;
  }

  .status-filing {
    background-color: #fff3e0;
    color: #f57c00;
  }

  .status-pre-trial {
    background-color: #fce4ec;
    color: #c2185b;
  }

  .status-trial {
    background-color: #f1f8e9;
    color: #558b2f;
  }

  .status-post-trial {
    background-color: #f3e5f5;
    color: #7b1fa2;
  }

  .status-execution {
    background-color: #e0f2f1;
    color: #00695c;
  }

  .status-closed {
    background-color: #e8f5e9;
    color: #2e7d32;
  }

  .status-withdrawn {
    background-color: #fafafa;
    color: #757575;
  }

  .status-terminated {
    background-color: #eeeeee;
    color: #757575;
  }

  /* 进度条样式 */
  .progress-item {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    flex: 1;
    min-width: 300px;
  }

  .progress-item .label {
    margin-bottom: 0;
    margin-right: 16px;
    white-space: nowrap;
  }

  .progress-container {
    flex: 1;
  }

  /* 三段式进度条样式 */
  .stage-progress-bar {
    display: flex;
    align-items: center;
    height: 32px;
    background-color: #f5f7fa;
    border-radius: 16px;
    overflow: hidden;
    position: relative;
  }

  .progress-stage {
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    cursor: pointer;
  }

  .progress-stage.pending {
    background-color: #e6f4ff;
    color: #1677ff;
  }

  .progress-stage.current {
    background-color: #ff8c00;
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(255, 140, 0, 0.3);
  }

  .progress-stage.completed {
    background-color: #52c41a;
    color: #fff;
  }

  .progress-stage:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 20px;
    background-color: rgba(255, 255, 255, 0.3);
  }

  .stage-text {
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 8px;
  }

  .stage-dot {
    position: absolute;
    right: -4px;
    top: 50%;
    transform: translateY(-50%);
    width: 8px;
    height: 8px;
    background-color: #fff;
    border-radius: 50%;
    border: 2px solid currentColor;
    z-index: 2;
  }

  .progress-stage:last-child .stage-dot {
    display: none;
  }

  .case-progress-bar {
    width: 100%;
  }

  .progress-text {
    font-size: 12px;
    font-weight: 500;
    color: #fff;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  :deep(.el-progress-bar__inner) {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-progress-bar__innerText) {
    display: none;
  }

  /* 平铺卡片布局样式 */
  .cards-layout {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-top: 20px;
  }

  .info-card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }

  .card-title {
    margin: 0;
    padding: 16px 20px;
    font-size: 16px;
    color: #303133;
    font-weight: 500;
    border-bottom: 1px solid #ebeef5;
    background-color: #f8f9fa;
  }

  .card-content {
    padding: 20px;
  }

  .card-toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-start;
  }

  /* 各卡片样式调整 */
  .contract-card .card-title {
    border-left: 4px solid #409eff;
  }

  .parties-card .card-title {
    border-left: 4px solid #67c23a;
  }

  .progress-card .card-title {
    border-left: 4px solid #e6a23c;
  }

  .documents-card .card-title {
    border-left: 4px solid #909399;
  }

  /* 响应式布局 - 四个卡片统一宽度设置 */
  .cards-layout {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  /* 当页面宽度足够时，卡片两个一行平均宽度排列 */
  @media screen and (min-width: 1200px) {
    .cards-layout {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
    }
  }

  /* 确保所有卡片具有相同的基础样式 */
  .info-card {
    width: 100%;
    min-width: 0; /* 防止flex/grid子元素溢出 */
  }

  /* 确保卡片内容有最小高度 */
  .card-content {
    min-height: 200px;
  }

  /* 标签页样式 */
  .case-detail-tabs {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  /* 基本信息区域样式 */
  .basic-info-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  /* 详细信息区域样式 */
  .detail-content-wrapper {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
  }

  .detail-column {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    display: flex;
    flex-direction: column;
  }

  .section-header {
    margin-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
  }

  .section-header h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }

  /* 使用更现代的卡片设计 */
  .info-section,
  .info-card {
    transition: all 0.3s ease;
  }

  .info-section:hover,
  .info-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  /* 响应式布局调整 */
  @media (max-width: 1200px) {
    .detail-content-wrapper {
      flex-direction: column;
    }
  }
</style>
